package com.jtjrenren.android.taxi.driver.manger;

import android.content.Context;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.jtjrenren.android.taxi.driver.Constants;
import com.jtjrenren.android.taxi.driver.R;
import com.jtjrenren.android.taxi.driver.base.BaseActivity;
import com.jtjrenren.android.taxi.driver.base.BaseApplication;
import com.jtjrenren.android.taxi.driver.bean.api.ApiCommonT;
import com.jtjrenren.android.taxi.driver.bean.api.Token;
import com.jtjrenren.android.taxi.driver.bean.event.ExitEvent;
import com.jtjrenren.android.taxi.driver.bean.event.UserInfoRefreshEvent;
import com.jtjrenren.android.taxi.driver.manger.api.PushWorks;
import com.jtjrenren.android.taxi.driver.manger.push.cmd.ControlCmd;
import com.jtjrenren.android.taxi.driver.bean.DriverInfo;
import com.jtjrenren.android.taxi.driver.manger.api.ApiWorks;

import com.jtjrenren.android.taxi.driver.utils.ModuleUtils;
import com.library.cache.ACache;
import com.library.utils.AppUtils;
import com.library.utils.LogUtil;
import com.library.utils.SpUtils;
import com.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by Administrator on 2016/8/26.
 * 全局业务管理
 */

public class AppManger {
    private static AppManger instance;

    public BaseActivity currentActivity;
    public int serial_no = 0;  //消息流水号
    public DriverInfo driver; //当前登录司机的信息
    public BDLocation currentLocation;
    public String gtCID;
    public String token;

    private Context context;
    private ACache aCache;

    private AppManger() {
    }

    public static AppManger getInstance() {
        if (instance == null)
            instance = new AppManger();
        return instance;
    }

    public void init(Context context) {
        this.context = context;
    }

    public void showTip(String desc) {
        if (context != null)
            Toast.makeText(context, desc, Toast.LENGTH_SHORT).show();
    }

    public String getResourceString(int id) {
        return context.getString(id);
    }

    public void setToken(String token) {
        LogUtil.log("token", "setToken()===> token:" + token);
        this.token = token;
        if (aCache == null)
            aCache = ACache.get(context);
        aCache.put(driver.getWorkNo() + "_token", token, 5 * ACache.TIME_DAY);

        if (!StringUtils.isEmpty(gtCID)) {
            bindGtID(gtCID);
        } else {
            LogUtil.log("token", "setToken  gtid is null");
        }
    }


    //设置个推ID
    public void setGtCID(String gtCID) {
        if (!StringUtils.isEmpty(this.gtCID) && gtCID.equals(this.gtCID))
            return;
        this.gtCID = gtCID;
        if (!StringUtils.isEmpty(this.token))
            bindGtID(gtCID);
    }

    //绑定个推ID
    public void bindGtID(String id) {
        LogUtil.log("token", "bindGtID()");
        PushWorks.bindGtID(id, new ApiWorks.ResponseListener<ApiCommonT>() {
            @Override
            public void onResponse(ApiCommonT apiCommonT) {
                if (apiCommonT != null && ModuleUtils.handCommon(apiCommonT.getCode())) {
                    LogUtil.log("token", "联网绑定gt 成功");
                }
            }
        });
    }

    //isRefresh 是否必须刷新
    public void getToken(boolean isRefresh) {
        LogUtil.log("token", "getToken() isRefresh:" + isRefresh);
        if (driver == null) {
            LogUtil.log("token", "getToken driver is null");
            return;
        }

        if (!isRefresh) {
            if (aCache == null)
                aCache = ACache.get(context);
            String asString = aCache.getAsString(driver.getWorkNo() + "_token");
            if (!StringUtils.isEmpty(asString)) {
                setToken(asString);
                return;
            }
        }

        PushWorks.getToken(driver.getMobilePhone(), getResourceString(R.string.appbz),
                AppUtils.getVersionName(context), new ApiWorks.ResponseListener<Token>() {
                    @Override
                    public void onResponse(Token token) {
                        if (token != null)
                            setToken(token.getToken());
                    }
                });
    }

    //登录成功
    public void loginSuccess(Context context, DriverInfo info) {
        LogUtil.log("user", "登录成功");
        driver = info;

        SpUtils.setParam(context, Constants.SP_DRIVER_REMBER, info.getWorkNo());
        SpUtils.setParam(context, Constants.SP_DRIVER_LASTLOGIN, info.getMobilePhone());

        //登录成功的相关操作
        startLocation();
        startCheckYYD();
        if (isSendLoc())
            startSendLocToControl();
        getToken(false);

        refreshDriverDetails(info.getWorkNo());
    }

    //是否上传定位
    public boolean isSendLoc() {
        if (driver == null)
            return false;
        return "mob".equals(AppManger.getInstance().driver.getTerminalType());
    }

    //更新司机的缓存
    private void refreshDriverCache(DriverInfo info) {
        if (aCache == null)
            aCache = ACache.get(context);
        aCache.remove(info.getWorkNo());
        aCache.put(info.getWorkNo(), info, 2 * ACache.TIME_DAY);
    }

    //刷新司机信息
    private void refreshDriverDetails(String driverID) {
        ApiWorks.getDriverDetails(driverID, new ApiWorks.ResponseListener<DriverInfo>() {
            @Override
            public void onResponse(DriverInfo driverInfo) {
                if (driverInfo != null) {
                    LogUtil.log("user", "司机的详细信息：" + driverInfo.toString());
                    refreshDriverInfo(driverInfo);
                }
            }
        });
    }

    //退出
    public void driverExit() {
        LogUtil.log("applog", "司机退出");
        driver = null;
        this.token = null;
        SpUtils.setParam(context, Constants.SP_DRIVER_REMBER, "");
        EventBus.getDefault().post(new ExitEvent());
        stopLocation();
        stopSendLocToControl();
        stopCheckYYD();
    }

    //上班
    public void driverOnDuty() {
        TtsManger.getInstance().speak("开始接单");
        String sbCmd = ControlCmd.getDriverWorkStatus(Constants.STATUS_DUTY_ON, ModuleUtils.getUniquePsuedoID(context));
        sendMsg(sbCmd);
    }

    //下班
    public void driverOffDuty() {
        String sbCmd = ControlCmd.getDriverWorkStatus(Constants.STATUS_DUTY_OFF, ModuleUtils.getUniquePsuedoID(context));
        sendMsg(sbCmd);

        SpUtils.setParam(context, Constants.SP_DRIVER_DUTY_ORDERCOUNT, 0);
    }

    //抢单成功
    public int qdSuccess() {
        int count = (int) SpUtils.getParam(context, Constants.SP_DRIVER_DUTY_ORDERCOUNT, 0) + 1;
        SpUtils.setParam(context, Constants.SP_DRIVER_DUTY_ORDERCOUNT, count);

        return count;
    }

    //更新司机账户信息
    public void refreshDriverInfo(DriverInfo info) {
        if (driver != null)
            info.setCarStatus(driver.getCarStatus());
        info.setDriverType(driver.getDriverType());
        info.setDriverChildType(driver.getDriverChildType());
        info.setTerminalType(driver.getTerminalType());

        refreshDriverCache(info);

        driver = info;

        EventBus.getDefault().post(new UserInfoRefreshEvent());
    }

    public Object getAcacheByKey(String key) {
        if (aCache == null)
            aCache = ACache.get(context);
        return aCache.getAsObject(key);
    }

    //开启预约单检查
    public void startCheckYYD() {

    }

    //关闭预约单检查
    public void stopCheckYYD() {
    }

    //是否是约租车
    public boolean isYzc() {
        return driver.getTerminalType().equals("mob")
                && driver.getDriverType() == Constants.DEF_DRIVER_TYPE_SPECAR;
    }

    //向服务器上传定位信息--开启
    private void startSendLocToControl() {
        if (BaseApplication.getInstance().mainService != null)
            BaseApplication.getInstance().mainService.startSendLoc();
    }

    //向服务器上传定位信息--关闭
    private void stopSendLocToControl() {
        if (BaseApplication.getInstance().mainService != null)
            BaseApplication.getInstance().mainService.stopSendLoc();
    }


    public void sendMsg(String msg) {
        if (driver == null || StringUtils.isEmpty(gtCID))
            return;
        PushWorks.pushMsg(msg, null);
    }


    //定位相关
    private LocationManger locationManger;

    public void startLocation() {
        if (locationManger == null) {
            locationManger = new LocationManger();
            locationManger.init(context);
        }
        locationManger.start();
    }

    public void stopLocation() {
        if (locationManger != null)
            locationManger.stop();
    }

    public void requestLocation() {
        if (locationManger != null)
            locationManger.request();
    }

}
